import axios from "axios";
import { getToken, removeToken } from "./cookie";
import router from "@/router";
//127.0.0.1:19090,向后端发起请求
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
const service = axios.create({
  baseURL: "/dev-api",
  timeout: 5000,
});
service.interceptors.request.use(
  (config) => {
  if (getToken()) {
  config.headers["Authorization"] = "Bearer " + getToken();
  }
  return config;
  },
  (error) => {
  console.log(error)
  Promise.reject(error);
  }
 );
service.interceptors.response.use(
  //成功也就是后端成功响应就可以了
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code;
    const msg = res.data.message;
    if(code==3001){
      ElMessage.error(msg);
      removeToken();
      router.push('/oj/login');
      return Promise.reject(new Error(msg));

    }
    if (code !== 1000) {
      ElMessage.error(msg);
      return Promise.reject(new Error(msg));
    } else {
      return Promise.resolve(res.data);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

//其他模块也能用
export default service